import { login,userGetData } from '@/api/user'
import { checkLoginStatus,removeSession } from '@/utils/auth'
import { resetRouter } from '@/router'

const getDefaultState = () => {
  return {
    isLogin: false,
    name: localStorage.getItem('username'),
    avatar: '',
    roles: [],
    info: {},
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_ISLOGIN: (state, isLogin) => {
    state.isLogin = isLogin
  },
  SET_NAME: (state, name) => {
    state.name = name;
    localStorage.setItem('username', name);

  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_INFO: (state, info) => {
    localStorage.setItem('Info', JSON.stringify(info));
    state.info = info;
  },
}

const actions = {
  // 登录
login({ commit }, userInfo) {
  const { username, password } = userInfo
  return new Promise((resolve, reject) => {
    login({ username: username.trim(), passwd: password }).then(res => {
      console.log(res);
      if (res.Ret == 'True') {
        commit('SET_INFO', res.Data);
        commit('SET_NAME', res.Data.username);
        let roles = ['超级管理员'];
        commit('SET_ROLES', roles);
        commit('SET_ISLOGIN', true);
        resolve()
        // 添加调试信息
        console.log('登录成功，准备跳转');
      } else {
        reject(res.Msg)
      }
    }).catch(error => {
      reject(error)
    })
  })
},

  // 获取用户信息（角色）每次请求都会 获取登录状态
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      const isLoggedIn = checkLoginStatus();
      if (isLoggedIn) {
        userGetData().then(res => {
          if (res.Ret == 'True') {
            const info = res.Data;
            let roles = ['超级管理员'];
            commit('SET_ROLES', roles);
            commit('SET_ISLOGIN', true);
            commit('SET_NAME', info.username);
            resolve(roles)
          } else {
            reject('获取用户信息失败')
          }
        }).catch(error => {
          reject(error)
        })
      } else {
        reject('验证失败,请重新登录')
      }
    })
  },

  // 登出
  logout({ commit }) {
    return new Promise((resolve, reject) => {
      localStorage.removeItem('Info')
      localStorage.removeItem('username')
      removeSession()

      resetRouter()
      commit('RESET_STATE')
      commit('SET_ROLES', [])
      resolve()
    })
  },

  // 重置状态
  resetState({ commit }) {
    return new Promise(resolve => {
      removeSession()
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}